package com.mallcai.bigdata.ladon.service.peekdata.sql;

import com.mallcai.bigdata.ladon.utils.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-03 11:43
 */
public class SelectSqlTemplate implements SqlTemplate{

    private String tableName;

    private List<SimpleSqlField> measureFieldList;

    private List<SimpleSqlField> dimensionFieldList;


    private List<FilterField> filterFieldList;


    public SelectSqlTemplate(String tableName, List<SimpleSqlField> simpleSqlFieldList, List<FilterField> filterFieldList) {
        this.tableName = tableName;
        this.filterFieldList = filterFieldList;
        Predicate<SimpleSqlField> predicate = (simpleSqlField) -> simpleSqlField.getAggFunction() != null;
        this.measureFieldList = simpleSqlFieldList.stream().filter(predicate).collect(Collectors.toList());
        this.dimensionFieldList = simpleSqlFieldList.stream().filter(predicate.negate()).collect(Collectors.toList());
    }

    public SelectSqlTemplate(String tableName, List<SimpleSqlField> simpleSqlFieldList) {
       this(tableName, simpleSqlFieldList, null);
    }


    @Override
    public String toSql() {
        StringBuilder ans = new StringBuilder(SqlConstants.SELECT);
        ans.append(SqlConstants.SPACE).append(getSelectedList())
            .append(SqlConstants.SPACE).append(SqlConstants.FROM)
            .append(tableName).append(SqlConstants.SPACE);

        if(CollectionUtils.isNotEmpty(this.filterFieldList)){
            ans.append(SqlConstants.WHERE).append(CollectionUtils.join(this.filterFieldList,SqlField::toSql, SqlConstants.AND));
        }

        if(CollectionUtils.isNotEmpty(this.dimensionFieldList) && CollectionUtils.isNotEmpty(this.measureFieldList)){
            ans.append(SqlConstants.GROUP_BY)
                .append(CollectionUtils.join(this.dimensionFieldList, SqlField::toSql));
        }

        return ans.toString() ;
    }

    private String getSelectedList() {
        List<SqlField> sqlFieldList = new ArrayList<>();
        sqlFieldList.addAll(this.dimensionFieldList);
        sqlFieldList.addAll(this.measureFieldList);
        return CollectionUtils.join(sqlFieldList, SqlField::toSql);
    }



}
